package com.mhs.map;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.mhs.BUS.BenhVienBUS;
import com.mhs.DTO.PlacemarkDTO;
import com.mhs.mydialog.MyDialogListner;
import com.mhs.services.PublicVariable;
import com.mhs.services.ServiceMap;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;

public class GetHospitalNear extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		// Intent myLocalIntent = intent.getIntent();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		// if no network is available networkInfo will be null
		// otherwise check if we are connected
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Bundle myBundle = intent.getExtras();
		double latitude;
		double longitude;
		latitude = myBundle.getDouble("latitude");
		longitude = myBundle.getDouble("longitude");
		if (isNetworkAvailable()) {
			try {
				requestToGetHospitalNear(latitude, longitude);
			} catch (Exception ex) {
				MyDialogListner.ShowMessageAlert(this,
						"Có lỗi xảy ra, vui lòng thử lại!");
				return;
			}
			// start activity GMap:
			Intent intentMap = new Intent();
			intentMap.setClass(GetHospitalNear.this, GMap.class);
			intentMap.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentMap); 
		} else {
			MyDialogListner.ShowMessageAlert(this,
					"Yêu cầu kết nối mạng cho ứng dụng!");
			return;
		}
	}

	private void requestToGetHospitalNear(double latitude, double longitude) {
		// https://maps.googleapis.com/maps/api/place/search/xml?location=10.835277%2C106.662707&radius=1000&keyword=b%E1%BB%87nh%20vi%E1%BB%87n&sensor=true&key=AIzaSyDjlqvj9KL536B3DAE52b6HTgAacZQS7DA
		String sLatitude = String.valueOf(latitude);
		String sLongitude = String.valueOf(longitude);
		String apiKey = PublicVariable.getApikey();
		String sRadius = PublicVariable.getRADIUS();
		String sSensor = PublicVariable.getSENSOR();
		String urlAddress = "https://maps.googleapis.com/maps/api/place/search/xml?location="
				+ sLatitude
				+ ","
				+ sLongitude
				+ "&radius="
				+ sRadius
				+ "&keyword=bệnh%20viện"
				+ "&sensor="
				+ sSensor
				+ "&key="
				+ apiKey;
		try {
			SoapObject so = ServiceMap.InvokeMethod(urlAddress);
			String sXML = "";
			if (so != null) {
				sXML = so.getProperty(0).toString();
			} else {
				sXML = "";
			}
			if (sXML.compareTo("") != 0 && sXML != null) {
				Document dom = DOMUtil.loadXMLFrom(sXML);
				List<PlacemarkDTO> lstPlacemarkDTO = parseDocToListHospital(dom);
				if (lstPlacemarkDTO != null && lstPlacemarkDTO.size() > 0) {
					// save lstPlacemarkDTO to db temp and db benhvien
					lstPlacemarkDTO = saveListPlacemark(lstPlacemarkDTO);
					addListPlaceMarkToPublicVar(lstPlacemarkDTO);
				} else {
					MyDialogListner.ShowMessageAlert(this,
							"Có lỗi xảy ra, vui lòng thử lại!");
					return;
				}
			}
		} catch (Exception e) {
			MyDialogListner.ShowMessageAlert(this,
					"Có lỗi xảy ra, vui lòng thử lại!");
			return;
		}
	}

	private List<PlacemarkDTO> parseDocToListHospital(Document dom) {
		List<PlacemarkDTO> lstPlaceMark = new ArrayList<PlacemarkDTO>();
		try {
			NodeList lstNodePlaceMark = dom.getElementsByTagName("result");
			if (lstNodePlaceMark.getLength() == 0 || lstNodePlaceMark == null) {
				MyDialogListner.ShowMessageAlert(this,
						"Không thông tin bệnh viện xung quanh vị trí của bạn!");
				return null;
			} else if (lstNodePlaceMark.getLength() > 0
					&& (lstNodePlaceMark != null)) {
				for (int i = 0; i < lstNodePlaceMark.getLength(); i++) {
					Element element = (Element) lstNodePlaceMark.item(i);
					PlacemarkDTO placeMarkDTO = new PlacemarkDTO();
					NodeList lstNodeName = element.getElementsByTagName("name");
					if (lstNodeName.getLength() == 1) {
						String valueOfNodeName = lstNodeName.item(0)
								.getTextContent().trim();
						placeMarkDTO.setName(valueOfNodeName);
					}
					NodeList lstLat = element.getElementsByTagName("lat");
					if (lstLat.getLength() == 1) {
						String valueOfNodeLat = lstLat.item(0).getTextContent()
								.trim();
						placeMarkDTO.setLatitude(valueOfNodeLat);
					}
					NodeList lstLng = element.getElementsByTagName("lng");
					if (lstLng.getLength() == 1) {
						String valueOfNodeLng = lstLng.item(0).getTextContent()
								.trim();
						placeMarkDTO.setLongitude(valueOfNodeLng);
					}
					NodeList lstRef = element.getElementsByTagName("reference");
					if (lstRef.getLength() == 1) {
						String valueOfNodeRef = lstRef.item(0).getTextContent()
								.trim();
						// request lay so phone ve:
						String urlAddress2 = "https://maps.googleapis.com/maps/api/place/details/xml?reference="
								+ valueOfNodeRef
								+ "&sensor="
								+ PublicVariable.getSENSOR()
								+ "&key="
								+ PublicVariable.getApikey();
						List<String> lstStr = getInfoSpecificFromGMap(urlAddress2);
						if (lstStr != null) {
							placeMarkDTO.setFoneNumber(lstStr.get(0));
							placeMarkDTO.setAddress(lstStr.get(1));
						} else {
							// set fone mac dinh 115
							placeMarkDTO.setFoneNumber("115");
							placeMarkDTO.setAddress("Chờ cập nhật");
						}
					}
					lstPlaceMark.add(placeMarkDTO);
				}
			}
		} catch (Exception ex) {
			MyDialogListner.ShowMessageAlert(this,
					"Có lỗi xảy ra, vui lòng thử lại!");
			return null;
		}
		return lstPlaceMark;
	}

	private List<String> getInfoSpecificFromGMap(String urlAddress2) {
		List<String> lstStr = new ArrayList<String>();
		try {
			SoapObject so = ServiceMap.getFoneNumberFromGMap(urlAddress2);
			String sXML = "";
			if (so != null) {
				sXML = so.getProperty(0).toString();
			} else {
				sXML = "";
			}
			if (sXML.compareTo("") != 0 && sXML != null) {
				Document dom = DOMUtil.loadXMLFrom(sXML);
				lstStr = parseDocToInfo(dom);
			}
		} catch (Exception e) {
			lstStr = new ArrayList<String>();
		}
		return lstStr;
	}

	private List<String> parseDocToInfo(Document dom) {
		List<String> lstStr = new ArrayList<String>();
		try {
			NodeList lstNodeResult = dom.getElementsByTagName("result");
			if (lstNodeResult.getLength() == 0 || lstNodeResult == null) {
				lstStr = new ArrayList<String>();
			} else if (lstNodeResult.getLength() > 0 && (lstNodeResult != null)) {
				if (lstNodeResult.getLength() == 1) {
					Element element = (Element) lstNodeResult.item(0);
					NodeList lstFoneNumber = element
							.getElementsByTagName("formatted_phone_number");
					if (lstFoneNumber.getLength() == 1) {
						String valueOfNodeRef = lstFoneNumber.item(0)
								.getTextContent().trim();
						//08 6288 8999
						// xu ly khoang trang trong chuoi
						if(checkCharacters(valueOfNodeRef, " ")){
							String[] arrTemp = valueOfNodeRef.split(" ");
							valueOfNodeRef = "";
							for(int i = 0;i < arrTemp.length;i++){
								valueOfNodeRef = valueOfNodeRef + arrTemp[i];
							}
						}else{
							// do nothing
						}
						lstStr.add(valueOfNodeRef);
					}
					NodeList lstAddress = element
							.getElementsByTagName("formatted_address");
					if (lstAddress.getLength() == 1) {
						String valueOfNodeAdd = lstAddress.item(0)
								.getTextContent().trim();
						lstStr.add(valueOfNodeAdd);
					}
				}
			}
		} catch (Exception e) {
			lstStr = new ArrayList<String>();
		}
		return lstStr;
	}

	private List<PlacemarkDTO> saveListPlacemark(List<PlacemarkDTO> lstPlaceMark) {
		List<PlacemarkDTO> lstPlaceMarkResult = new ArrayList<PlacemarkDTO>();
		for (int i = 0; i < lstPlaceMark.size(); i++) {
			PlacemarkDTO pmDTO = lstPlaceMark.get(i);
			BenhVienBUS bvBUS = new BenhVienBUS();
			boolean checkInsert = bvBUS.insertPlaceMarkDTOIntoBenhVien(
					getApplicationContext(), pmDTO);
			if (checkInsert) {
				lstPlaceMarkResult.add(pmDTO);
			} else {
				// do nothing
			}
		}
		return lstPlaceMarkResult;
	}

	private void addListPlaceMarkToPublicVar(List<PlacemarkDTO> lstPlaceMark) {
		if (lstPlaceMark == null) {
			return;
		} else {
			PublicVariable.setLstPlaceMark(lstPlaceMark);
		}
	}
	
	public boolean checkCharacters(String query, String characterCheck) {
		boolean check = false;
		char[] cArray = convertStringToCharArray(query);
		for (int i = 0; i < cArray.length; i++) {
			if (Character.toString(cArray[i]).compareTo(characterCheck) == 0) {
				check = true;
				break;
			} else {
				check = false;
			}
		}
		return check;
	}
	
	public char[] convertStringToCharArray(String query) {
		return query.toCharArray();
	}

}
